﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TamTreSoSinh.DBContext;

namespace TamTreSoSinh
{
    public partial class ProductDetailPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadProductInfo();
            LoadShoppingCategory();
        }

        private void LoadShoppingCategory()
        {
            DBTamTreEntities dbcontext = new DBTamTreEntities();
            List<ShoppingCategory> listShoppingCategory = dbcontext.ShoppingCategories.Where(obj => obj.IsVisible).OrderBy(obj => obj.Priority).ToList();

            rptShoppingCategory.DataSource = listShoppingCategory;
            rptShoppingCategory.DataBind();
        }

        protected void rptShoppingCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ShoppingCategory shoppingCategory = (ShoppingCategory)e.Item.DataItem;
            HyperLink hpl = (HyperLink)e.Item.FindControl("hplShoppingCategory");
            hpl.NavigateUrl = @"/ShoppingCategoryPage.aspx#AnchorShopping" + shoppingCategory.Id;
            hpl.Text = shoppingCategory.Title;
        }

        private void LoadProductInfo()
        {
            DBTamTreEntities dbcontext = new DBTamTreEntities();
            int Id;
            bool isValidId = int.TryParse(Request["Id"], out Id);
            if (!isValidId)
            {
                return;
            }

            Product product = dbcontext.Products.FirstOrDefault(obj => obj.Id == Id);
            if (product == null)
            {
                return;
            }

            if (!product.IsInStock)
            {
                divInStock.Visible = false;
            }

            List<string> listStar = new List<string>();
            for (int i = 1; i <= product.Rate; i++)
            {
                listStar.Add(string.Empty);
            }

            rptStar.DataSource = listStar;
            rptStar.DataBind();

            lblTitleTop.Text = product.ProductName;
            hplShoppingCategory.Text = product.ShoppingCategory.Title;
            hplShoppingCategory.NavigateUrl = @"/ShoppingPage.aspx?Id=" + product.ShoppingCategoryId;
            lblProductName.Text = product.ProductName;
            ImgProduct.NavigateUrl = product.ImagePath;
            ImgProduct.ImageUrl = product.ImagePath;

            lblOverview.Text = product.Overview;

            if (product.OldPrice.HasValue)
            {
                lblOldPrice.Text = string.Format("{0:#,##0}", product.OldPrice.Value).Replace(",", ".") + " VND";
                lblOldPrice.Visible = true;
            }

            lblCurrentPrice.Text = string.Format("{0:#,##0}", product.CurrentPrice).Replace(",", ".") + " VND";
            ltrDescription.Text = product.Description;
        }
    }
}